package com.fujin.gulimall.cart.Interceptor;

import com.fujin.common.Vo.MemberRsepVo;
import com.fujin.common.constant.AuthServerConstant;
import com.fujin.common.constant.CartConstant;
import com.fujin.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @title: CartInterceptor
 * @Author uIn
 * @Date: 2022/3/13 16:06
 * @Version 1.0
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal();

    /**
     * 前置拦截 请求之前拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberRsepVo memberRsepVo = (MemberRsepVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        //判断是否登录
        if (memberRsepVo != null){
            //已登录
            userInfoTo.setUserId(memberRsepVo.getId());
        }

        //获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                //user-key
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){
                    userInfoTo.setUserKey(cookie.getValue());
                    // 标识客户端已经存储了 user-key
                    userInfoTo.setTempUser(true);
                }
            }
        }

        //当第一次访问购物车的时候cookie中是没有 ‘user-key’的，所有需要在第一次添加cookie
        if (StringUtils.isBlank(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        //存入threadLocal
        threadLocal.set(userInfoTo);

        return true;
    }

    /**
     * 后置拦截 请求之后拦截
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //业务执行之后，让浏览器保存临时用户user-key
        //通过cookie的形式保存
        UserInfoTo userInfoTo = threadLocal.get();
        if (userInfoTo != null && !userInfoTo.isTempUser()){
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
